package cn.mw.cmdb.entity;

import cn.mw.cmdb.enums.CompareRuleEnum;
import cn.mw.cmdb.param.ImportContextParam;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.MPropertyTypeTime;
import cn.mw.microMonitorCommon.entity.cmdb.ModelExportDataInfoParam;
import cn.mw.microMonitorCommon.entity.cmdb.MwImportResultParam;
import cn.mw.microMonitorCommon.util.DateUtils;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.util.ValConvertUtil.intValueConvert;

@Slf4j
public class PropertyTypeTime extends PropertyType<PropertyTypeTime, Date> {

    private final String formate = "yyyy-MM-dd HH:mm:ss";
    public static final String ID = MPropertyTypeTime.ID;
    public static final String StartTimeKey = "startTime";
    public static final String EndTimeKey = "endTime";
    private static List<String> finalList = new ArrayList<>();

    private MPropertyTypeTime mPropertyTypeTime = new MPropertyTypeTime();

    public PropertyTypeTime() {
        setId(ID);
        setName("时间");
        setValueTip(formate);
        setSortNum(8);
    }

    @Override
    public Object tableHeaderTipInfo(PropertyTypeRef propertyTypeRef) {
        return "时间格式:" + formate;
    }

    @Override
    public Object convertValue(Object value) {
        if (Strings.isNullOrEmpty(strValueConvert(value))) {
            return "";
        }
        if (value instanceof String) {
            Date date = null;
            try {
                date = DateUtils.parse(value.toString());
            } catch (Exception e) {
                log.warn("convertValue:{}", e);
            }
            return date;
        }
        return (Date) value;
    }

    @Override
    public Criteria doCriteria(CriteriaOpsType opsType, String name, Object value) {
        return mPropertyTypeTime.doCriteria(opsType, name, value);
    }

    @Override
    public CriteriaOpsType getDefaultCriteriaOpsType() {
        return CriteriaOpsType.lte;
    }

    @Override
    public PropertyTypeTime newObj() {
        return new PropertyTypeTime();
    }

    @Override
    public Object readValue(Object val, Map<String, Object> context) {
        if (val != null && val instanceof Date) {
            String format = cn.mw.microMonitorCommon.util.DateUtils.format((Date) val, formate);
            return format;
        }
        return null;
    }

    @Override
    public Object exportValue(Object val, Map<String, Object> context) {
        return readValue(val, context);
    }

    @Override
    public Object checkValue(Object val, Map<String, Object> context) {
        return readValue(val, context);
    }

    @Override
    public void refresh() {
        finalList.clear();
    }

    @Override
    public Object getDataValue(ImportContextParam contextParam) {
        MwImportResultParam resultParam = new MwImportResultParam();
        String message = "";
        ModelExportDataInfoParam importParam = contextParam.getParam();
        //属性名称
        String tableName = importParam.getTableName();
        Object cellValue = importParam.getCellValue();
        Map<String, Object> matchMap = new HashMap<>();
        importCheckInfo(resultParam, contextParam, matchMap);
        Date parse = DateUtils.parse(strValueConvert(cellValue));
        boolean isDefaultFlag = false;
        //数值类型为空字符串，默认为0
        if (Strings.isNullOrEmpty(strValueConvert(cellValue).trim())) {
            //空字符串
            if (matchMap != null && matchMap.get(ValueKey) != null) {
                Object obj = matchMap.get(ValueKey);
                isDefaultFlag = true;
                cellValue = obj;
            } else {
                return resultParam;
            }
        }
        //是否默认值提示
        String prefixStr = prefixStrKey;
        if (isDefaultFlag) {
            prefixStr = defaultPrefixStrKey;
        }
        if (parse == null) {
            message += tableName + prefixStr + strValueConvert(cellValue).trim() + "]时间格式不正确:" + formate;
            resultParam.setMessage(message);
            return resultParam;
        }
        if (matchMap != null) {
            //比较值类型（1：固定值，2：选择关联属性值,3:当前时间）
            Integer dateCompare = intValueConvert(matchMap.get(dateCompareKey));
            //比较规则(大于，小于。。)
            String compareRule = strValueConvert(matchMap.get(compareRuleKey));
            //比较值
            String compareValue = strValueConvert(matchMap.get(compareValueKey));
            //固定值校验
            if (dateCompare.intValue() == 1) {
                if (!Strings.isNullOrEmpty(compareRule) && !Strings.isNullOrEmpty(compareValue)) {
                    message += getTimeCompare(compareValue, tableName, compareRule, fixedValStrKey, resultParam, strValueConvert(cellValue), prefixStr);
                }
            }
            //选择关联属性值校验
            if (dateCompare.intValue() == 2) {
                String comparePropertyId = compareValue;
                List<ModelExportDataInfoParam> collect = contextParam.getListInfos().stream().filter(s -> s.getRowNum() == importParam.getRowNum() && s.getPropertyId().equals(comparePropertyId)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    ModelExportDataInfoParam compareDataInfoParam = collect.get(0);
                    String selectTableName = compareDataInfoParam.getTableName();
                    String selectValue = strValueConvert(compareDataInfoParam.getCellValue());
                    if (Strings.isNullOrEmpty(selectValue)) {
                        message += tableName + "指定的比较时间:[" + selectTableName + "]不能为空";
                    } else {
                        message += getTimeCompare(selectValue, tableName, compareRule, selectTableName, resultParam, strValueConvert(cellValue), prefixStr);
                    }
                }
            }
            //当前时间校验
            if (dateCompare.intValue() == 3) {
                String format = DateUtils.format(new Date(), formate);
                if (!Strings.isNullOrEmpty(compareRule) && !Strings.isNullOrEmpty(format)) {
                    message += getTimeCompare(format, tableName, compareRule, currentTimeStrKey, resultParam, strValueConvert(cellValue), prefixStr);
                }
            }
        }

        resultParam.setMessage(message);
        resultParam.setCellValue(DateUtils.format(parse, formate));
        return resultParam;

    }

    public static String getTimeCompare(String compareValue, String tableName, String compareRule,
                                        String selectTableName, MwImportResultParam resultParam, String cellValue, String prefixStr) {
        String message = resultParam.getMessage();
        Date parse = DateUtils.parse(cellValue);
        Date selectValueParse = DateUtils.parse(compareValue);
        if (parse == null) {
            message += tableName + prefixStr + strValueConvert(cellValue).trim() + "]格式不正确";
            return message;
        }
        if (selectValueParse == null) {
            if (selectTableName == null) {
                message += tableName + "指定的比较时间格式设置出错";
            } else {
                message += tableName + "指定的比较时间:[" + selectTableName + "]格式设置出错";
            }
        } else {
            String titleInfo = "";
            if (selectTableName == null) {
                titleInfo = "固定值";
            } else {
                titleInfo = selectTableName;
            }

            //当前值时间 - 比较值得时间
            long compare = parse.getTime() - selectValueParse.getTime();
            //大于
            if (CompareRuleEnum.gt.getName().equals(compareRule) && (compare <= 0)) {
                message += tableName + prefixStr + cellValue + "]必须大于" + titleInfo + ":[" + compareValue + "]";
            }
            //大于等于
            if (CompareRuleEnum.ge.getName().equals(compareRule) && (compare < 0)) {
                message += tableName + prefixStr + cellValue + "]必须大于等于" + titleInfo + ":[" + compareValue + "]";
            }
            //小于
            if (CompareRuleEnum.lt.getName().equals(compareRule) && (compare >= 0)) {
                message += tableName + prefixStr + cellValue + "]必须小于" + titleInfo + ":[" + compareValue + "]";
            }
            //小于等于
            if (CompareRuleEnum.le.getName().equals(compareRule) && (compare > 0)) {
                message += tableName + prefixStr + cellValue + "]必须小于等于" + titleInfo + ":[" + compareValue + "]";
            }
            //不等于
            if (CompareRuleEnum.ne.getName().equals(compareRule) && (compare == 0)) {
                message += tableName + prefixStr + cellValue + "]不能等于" + titleInfo + ":[" + compareValue + "]";
            }
        }
        return message;
    }


}
